package com.lihonghao.channel;

import com.lihonghao.handle.HttpRequestHandler;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.SocketException;
import java.util.concurrent.atomic.AtomicLong;

public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        // 日志记录
        pipeline.addLast("logging", new LoggingHandler(LogLevel.DEBUG));
        // http 编解码
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast("httpAggregator", new HttpObjectAggregator(1024 * 1024)); // http 消息聚合器
        pipeline.addLast(new HttpRequestHandler());// 请求处理器
//        pipeline.addLast(new IdleStateHandler(0, 0, 10));// 10秒无活动则关闭
//        pipeline.addLast(new ChannelInboundHandlerAdapter(){
//            @Override
//            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
//                if (evt instanceof IdleStateEvent) {
//                    ctx.close(); // 空闲超时关闭连接
//                }
//            }
//        });
    }

    private static final AtomicLong ACCESS_COUNT = new AtomicLong(0);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof SocketException && "Connection reset".equals(cause.getMessage())) {
            // 记录连接重置日志（级别设为 DEBUG，避免刷屏）
            long count = ACCESS_COUNT.incrementAndGet();
            System.out.println("强制关闭"+count);
        } else {
            // 其他异常记录错误日志并关闭连接
            long count = ACCESS_COUNT.incrementAndGet();
            System.out.println("强制关闭"+count);
            ctx.close();
        }
    }

}
